<template>
  <div class="profile-wrapper">
    <div class="profile-container">
      <div class="profile-header">
        <h1>个人信息管理</h1>
        <p>管理您的个人资料和账户安全</p>
      </div>
      
      <div class="profile-content">
        <div class="profile-section">
          <h2>基本信息</h2>
          <form @submit.prevent="updateProfile" class="profile-form">
            <div class="form-row">
              <div class="form-group">
                <label for="username">用户名</label>
                <input 
                  id="username" 
                  v-model="profileForm.username" 
                  type="text" 
                  :disabled="!isEditing"
                  required
                />
              </div>
              
              <div class="form-group">
                <label for="email">邮箱</label>
                <input 
                  id="email" 
                  v-model="profileForm.email" 
                  type="email" 
                  :disabled="!isEditing"
                  required
                />
              </div>
            </div>
            
            <div class="form-row">
              <div class="form-group">
                <label for="phone">手机号</label>
                <input 
                  id="phone" 
                  v-model="profileForm.phone" 
                  type="tel" 
                  :disabled="!isEditing"
                />
              </div>
              
              <div class="form-group">
                <label for="role">用户角色</label>
                <input 
                  id="role" 
                  :value="getRoleText(profileForm.role)" 
                  type="text" 
                  disabled
                />
              </div>
            </div>
            
            <div class="form-actions">
              <button 
                v-if="!isEditing" 
                type="button" 
                @click="startEditing" 
                class="edit-button"
              >
                编辑信息
              </button>
              <div v-else>
                <button type="submit" class="save-button">保存</button>
                <button type="button" @click="cancelEditing" class="cancel-button">取消</button>
              </div>
            </div>
          </form>
        </div>
        
        <div class="profile-section">
          <h2>修改密码</h2>
          <form @submit.prevent="changePassword" class="password-form">
            <div class="form-group">
              <label for="oldPassword">当前密码</label>
              <input 
                id="oldPassword" 
                v-model="passwordForm.oldPassword" 
                type="password" 
                required
              />
            </div>
            
            <div class="form-group">
              <label for="newPassword">新密码</label>
              <input 
                id="newPassword" 
                v-model="passwordForm.newPassword" 
                type="password" 
                required
                minlength="6"
              />
            </div>
            
            <div class="form-group">
              <label for="confirmPassword">确认新密码</label>
              <input 
                id="confirmPassword" 
                v-model="passwordForm.confirmPassword" 
                type="password" 
                required
              />
            </div>
            
            <button type="submit" class="change-password-button">修改密码</button>
          </form>
        </div>
      </div>
      
      <div class="profile-footer">
        <button @click="goBack" class="back-button">返回首页</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import api from '../api/index.js'

const router = useRouter()
const isEditing = ref(false)

// 获取存储的用户信息
const currentUser = JSON.parse(localStorage.getItem('user') || '{}')

const profileForm = reactive({
  id: currentUser.userId || '',
  username: currentUser.username || '',
  email: currentUser.email || '',
  phone: currentUser.phone || '',
  role: currentUser.role !== undefined ? currentUser.role : ''
})

const originalProfile = { ...profileForm }

const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 获取角色文本
const getRoleText = (role) => {
  switch (role) {
    case 0: return '管理员'
    case 1: return '普通用户'
    default: return '未知'
  }
}

// 开始编辑
const startEditing = () => {
  isEditing.value = true
}

// 取消编辑
const cancelEditing = () => {
  isEditing.value = false
  // 恢复原始数据
  Object.assign(profileForm, originalProfile)
}

// 更新个人信息
const updateProfile = async () => {
  try {
    const response = await api.post('/user/update', {
      id: profileForm.id,
      username: profileForm.username,
      email: profileForm.email,
      phone: profileForm.phone
    })
    
    if (response.code === 0) {
      alert('个人信息更新成功')
      isEditing.value = false
      // 更新本地存储的用户信息
      const updatedUser = { ...currentUser, ...profileForm }
      localStorage.setItem('user', JSON.stringify(updatedUser))
      Object.assign(originalProfile, profileForm)
    } else {
      alert(response.message || '更新失败')
    }
  } catch (error) {
    console.error('更新失败:', error)
    alert('更新失败，请稍后重试')
  }
}

// 修改密码
const changePassword = async () => {
  // 验证新密码和确认密码是否一致
  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    alert('新密码和确认密码不一致')
    return
  }
  
  try {
    const response = await api.post('/user/reset-password', {
      email: profileForm.email,
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword,
      confirmNewPassword: passwordForm.confirmPassword
    })
    
    if (response.code === 0) {
      alert('密码修改成功')
      // 清空密码表单
      passwordForm.oldPassword = ''
      passwordForm.newPassword = ''
      passwordForm.confirmPassword = ''
    } else {
      alert(response.message || '密码修改失败')
    }
  } catch (error) {
    console.error('密码修改失败:', error)
    alert('密码修改失败，请稍后重试')
  }
}

// 返回首页
const goBack = () => {
  // 根据用户角色返回对应的首页
  if (currentUser.role === 0) {
    router.push('/admin')
  } else {
    router.push('/user')
  }
}

onMounted(() => {
  // 可以在这里添加获取用户详细信息的逻辑
})
</script>

<style scoped>
.profile-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  width: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  box-sizing: border-box;
}

.profile-container {
  width: 100%;
  max-width: 800px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  padding: 30px;
  box-sizing: border-box;
}

.profile-header {
  text-align: center;
  margin-bottom: 30px;
}

.profile-header h1 {
  color: #333;
  font-size: 32px;
  margin-bottom: 10px;
}

.profile-header p {
  color: #666;
  font-size: 18px;
}

.profile-content {
  display: flex;
  flex-direction: column;
  gap: 30px;
  margin-bottom: 30px;
}

.profile-section {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 25px;
}

.profile-section h2 {
  color: #333;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #eee;
}

.profile-form, .password-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-row {
  display: flex;
  gap: 20px;
}

.form-group {
  flex: 1;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #333;
  font-weight: 500;
}

.form-group input {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 16px;
  transition: border-color 0.3s;
  box-sizing: border-box;
}

.form-group input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
}

.form-group input:disabled {
  background-color: #f5f5f5;
  cursor: not-allowed;
}

.form-actions {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.edit-button, .save-button, .cancel-button, .change-password-button, .back-button {
  padding: 12px 24px;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.edit-button {
  background: #667eea;
  color: white;
}

.edit-button:hover {
  background: #5a6fd8;
}

.save-button {
  background: #28a745;
  color: white;
}

.save-button:hover {
  background: #218838;
}

.cancel-button {
  background: #6c757d;
  color: white;
}

.cancel-button:hover {
  background: #5a6268;
}

.change-password-button {
  background: #ffc107;
  color: #212529;
  align-self: flex-start;
}

.change-password-button:hover {
  background: #e0a800;
}

.back-button {
  background: #17a2b8;
  color: white;
  margin: 0 auto;
  display: block;
}

.back-button:hover {
  background: #138496;
}

.profile-footer {
  text-align: center;
}

@media (max-width: 768px) {
  .form-row {
    flex-direction: column;
    gap: 0;
  }
  
  .profile-container {
    padding: 20px;
  }
  
  .profile-section {
    padding: 20px;
  }
}
</style>